<script setup>
import { h, ref } from 'vue'
import { MenuRouter } from '@/router'
import { RouterLink } from 'vue-router'
import { useI18n } from 'vue-i18n'
import { NIcon } from 'naive-ui'
import alarmIcon from '@/components/iconSvg/alarmIcon.vue'
import dataIcon from '@/components/iconSvg/dataIcon.vue'
import permissionIcon from '@/components/iconSvg/permissionIcon.vue'
import systemIcon from '@/components/iconSvg/systemIcon.vue'
import deviceIcon from '@/components/iconSvg/deviceIcon.vue'

const iconMapping = {
  alarmIcon: alarmIcon,
  dataIcon: dataIcon,
  permissionIcon: permissionIcon,
  systemIcon: systemIcon,
  deviceIcon: deviceIcon
}
const { t } = useI18n()

// 菜单相关
const menuOptions = ref([])
/**
 * 处理菜单数据
 * @param route
 * @param parentPath
 */
const dealMenuData = (route, parentPath) => {
  let menuList = []
  route.forEach((item) => {
    if (item?.meta?.isMenu) {
      let menuItem = {}
      let path = parentPath + '/' + item.path
      menuItem.label = item.path
      menuItem.key = item.path
      menuItem.path = path
      menuItem.customIcon = item?.meta?.icon
      menuItem.size = item?.meta?.size ? item?.meta?.size : 24
      if (item.children) {
        menuItem.children = dealMenuData(item.children, path)
      }
      menuList.push(menuItem)
    }
  })
  return menuList
}
/**
 * 生成菜单项
 */
const createMenu = () => {
  let menuList = dealMenuData(MenuRouter.children, '/home')
  menuOptions.value = menuList
}
createMenu()

const props = defineProps({
  collapsed: {
    require: true,
    type: Boolean
  }
})

const renderMenuLabel = (option) => {
  if ('path' in option && !option.children) {
    return h(
      RouterLink,
      {
        to: option.path
      },
      { default: () => t(`menu.${option.label}`) }
    )
  }
  return t(`menu.${option.label}`)
}
const renderMenuIcon = (option) => {
  if (!option.customIcon) return null
  return h(
    NIcon,
    {
      size: option.size
    },
    { default: () => h(iconMapping[option.customIcon], null, {}) }
  )
}
</script>

<template>
  <n-menu
    class="h-full overflow-y-scroll"
    :collapsed="props.collapsed"
    :collapsed-width="64"
    :collapsed-icon-size="22"
    :options="menuOptions"
    :render-label="renderMenuLabel"
    :render-icon="renderMenuIcon"
    style="scrollbar-width: none; -ms-overflow-style: none"
  />
  <!-- accordion -->
</template>

<style scoped></style>
